package modelLayer;

import java.io.IOException;
import java.util.ArrayList;

import uiLayer.SaveToFile;


public class ProductRecords {

	private static ProductRecords instance = null;
	private int uniqueId;
	private ArrayList<Product> products;

public ProductRecords(){
	products = new ArrayList<Product>();
	uniqueId=0;
}
public static ProductRecords getInstance()       
{
	if(instance == null)
	{
		instance = new ProductRecords();
	}
	return instance;
}
public ArrayList<Product> getProducts() {
	return products;
}
public int createItem(String contrID,String measure, String name, String description, double price, double quantity, String category, String location, double alert)
{
	uniqueId++;
	Product prod = new Product(uniqueId,name,description,price,quantity,category,location,alert,measure);
	products.add(prod);
	SLIRecords.getInstance().createSLI(prod);
	Contractor contr = ContractorRecords.getInstance().findContractor(contrID);
	contr.setMoneyPaid(price*quantity);
	try{
		contr.getProducts().add(prod);
	}
	catch(NullPointerException nPE){
		System.out.println("Contractor doesn't exist: Try again");
	}
	return uniqueId;
	}


/**
 * @param uniqueId the uniqueId to set
 */
public void setUniqueId(int uniqueId) {
	this.uniqueId = uniqueId;
}
public String findItem(int Id) throws NullPointerException
{
	String found = null;
	for(Product p1: products){
		if(p1.getId()==Id)found = p1.toString();
	}
	if(found==null)throw new NullPointerException("Product doesn't exist!");
	return found;
}
public Product getItem(String id) {
	for(Product p1: products){
		if(p1.getId()==Integer.parseInt(id))return p1;
	}
	
	return null;

}
public void deleteItem(String id)
{
	products.remove(getItem(id));
}
public void saveProd() throws IOException{
	for(Product p1: products){
		SaveToFile.getInstance().save(p1.save());
		
	}
}
/*
 * update item even if company makes a new order of product, which exist in system
 * 
 */
public void updateItem(String Id, String contID, double quantity, String location, double price, double alert)
{
	Product p1 = getItem(Id);
	if(location!=null)p1.setLocation(location);
	if(quantity!=0)p1.setQuantity(p1.getQuantity()+quantity);
	if(price!=0)p1.setPrice(price);
	if(alert!=0)p1.setAlert(alert);
	
}

}

